package com.bkhc.common.service;

import com.bkhc.common.entity.ApiInfo;
import com.bkhc.common.entity.Role;
import com.bkhc.common.entity.User;
import com.bkhc.common.entity.UserRole;
import com.bkhc.common.exception.CustomException;
import com.bkhc.common.permissions.bean.RoleDetail;
import com.bkhc.common.permissions.bean.UserPermission;
import com.bkhc.common.repository.*;
import com.bkhc.common.util.CommonUtil;
import com.bkhc.common.util.MyBeanUtils;
import com.bkhc.common.util.response.PageUtil;
import com.bkhc.common.util.response.ResultCode;
import com.bkhc.common.util.response.ResultJson;
import com.bkhc.common.vo.UserBean;
import com.bkhc.common.vo.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserService {

    @Autowired
    private UserRepository repository;
    @Autowired
    private RoleRepository roleRepository;
    @Autowired
    private UserRoleRepository userRoleRepository;
    @Autowired
    private ApiInfoRepository apiInfoRepository;
    @Autowired
    private UmcRepository umcRepository;
    public ResultJson<?> queryUser(UserVo userVo, int pageIndex, int pageSize){

        Sort.Order orders = new Sort.Order(Sort.Direction.DESC, "updateDate");
        PageRequest pageRequest = PageRequest.of(pageIndex-1, pageSize, Sort.by(orders));
        Page<User> users = null;
        if(userVo == null){
           users = repository.findAll(pageRequest);
        }else {
            User user = new User();
            BeanUtils.copyProperties(userVo,user);
            users = repository.findAll(user, pageRequest);
        }
        PageUtil pageUtil = new PageUtil(users);
        ResultJson<PageUtil> resultJson = ResultJson.success();
        resultJson.setData(pageUtil);
        return resultJson;

    }

    public ResultJson<?> queryUserByRoleCode(String roleCode) {
        List<UserRole> userRole = userRoleRepository.findByRoleCode(roleCode);
        List<String> userIdList = userRole.stream().map(UserRole::getUserId).collect(Collectors.toList());
        List<User> userList = repository.findByUserIdIn(userIdList);
        return ResultJson.ok(userList);
    }

    public User queryByUsername(String username){
        return repository.findByUsername(username);
    }

    public ResultJson<?> addUser(User user) {
        User old = repository.findByUserId(user.getUserId());
        if(old != null){
            throw new CustomException(ResultJson.failure(ResultCode.ISEXIT_RESURCE));
        }
        User u = umcRepository.findByUserId(user.getUserId());
        repository.save(u);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> updateUser(User user) {
        User userOld = repository.findByUserId(user.getUserId());
        MyBeanUtils.copyProperties(user,userOld);
        repository.save(userOld);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> delete(User user) {
        repository.delete(user);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<User> getUserRole(String userId, int status) {
        ResultJson<User> resultJson = null;
        User user = repository.findByUserId(userId);
        user.setRoles(roleRepository.findAllByUserIdAndStatus(userId,status));
        resultJson = ResultJson.success();
        resultJson.setData(user);
        return resultJson;
    }

    public ResultJson<User> getUserRole(String userId) {
        ResultJson<User> resultJson = null;
        User user = repository.findByUserId(userId);
        user.setRoles(roleRepository.findAllByUserId(userId));
        resultJson = ResultJson.success();
        resultJson.setData(user);
        return resultJson;
    }

    public ResultJson<?> queryUserRoleDetail(String userId) {
        ResultJson<List<Role>> resultJson = null;
        List<Role> roles = repository.findRoleByUserId(userId);
        resultJson = ResultJson.success();
        resultJson.setData(roles);
        return resultJson;
    }

    public ResultJson<?> updateUserRoleDetail(UserRole userRole) {
//        Optional<UserRole> optional = userRoleRepository.findById(userRole.getId());
//        UserRole oldUserRole = optional.get();
//        MyBeanUtils.copyProperties(userRole,oldUserRole);
//        userRoleRepository.save(oldUserRole);
        return ResultJson.success();
    }

    public ResultJson<?> queryUserByUserId(String userId) {
        User u = repository.findByUserId(userId);
        if (u==null){
            u = umc.findByUserId(userId);
        }
        return ResultJson.ok(u);
    }

    @Autowired
    private UmcRepository umc;


    public User getUserByUserId(String userId) {
        User u = repository.findByUserId(userId);
        if (u==null){
            u = umc.findByUserId(userId);
        }
        return u;
    }

    public List<User> getUserByUsername(String username) {
        return umc.getUserByUsername(username);
    }

    public UserPermission queryUserPermission(String userId) {
        UserPermission permission = new UserPermission();
        User u = repository.findByUserId(userId);
        if(u == null){
            return  null;
        }
        permission.setUserId(userId);
        permission.setUsername(u.getUsername());
        List<Role> roleList = roleRepository.findAllByUserId(userId);
        if(!CollectionUtils.isEmpty(roleList)){
            List<RoleDetail> roleDetails = new ArrayList<>();
            for(Role role : roleList){
                List<ApiInfo> apiinfos = apiInfoRepository.findAllByRoleCode(role.getRoleCode());
                RoleDetail roleDetail = new RoleDetail();
                roleDetail.setRole_code(role.getRoleCode());
                roleDetail.setRole_name(role.getRoleName());
                roleDetail.setApiInfos(apiinfos);
                roleDetails.add(roleDetail);
            }
            permission.setRoles(roleDetails);

        }else{
            List<RoleDetail> roleDetails = new ArrayList<>();
            for(Role role : roleList){
                List<ApiInfo> apiinfos = apiInfoRepository.findAllByRoleCode("default");
                RoleDetail roleDetail = new RoleDetail();
                roleDetail.setRole_code(role.getRoleCode());
                roleDetail.setRole_name(role.getRoleName());
                roleDetail.setApiInfos(apiinfos);
                roleDetails.add(roleDetail);
            }
            permission.setRoles(roleDetails);
        }
        return permission;
    }

    public ResultJson<?> updateStatus(String userId, String status) {
        User user = repository.findByUserId(userId);
        user.setStatus(status);
        repository.save(user);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }

    public ResultJson<?> saveOrupdateUserRole(UserRole userRole) {
        userRoleRepository.deleteByUserId(userRole.getUserId());
        UserRole userRoleEntity = new UserRole();
        userRoleEntity.setRoleCode(userRole.getRoleCode());
        userRoleEntity.setUserId(userRole.getUserId());
        userRoleEntity.setStatus("1");
        UserBean cureentUser = CommonUtil.getCrruentUser();
        userRoleEntity.setCreator(cureentUser.getUserId());
        userRoleEntity.setUpdator(cureentUser.getUserId());
        userRoleRepository.save(userRole);
        ResultJson<?> resultJson = ResultJson.success();
        return resultJson;
    }
}
